package com.kin207.netty.handle.adapter;

import java.util.Collection;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kin207.netty.handle.IMessageHandle;
import com.kin207.netty.handle.IMessageHandleAdapter;
import com.kin207.netty.handle.MessageHandles;

public class HexHeadMessageHandleAdapter implements IMessageHandleAdapter {
	final static Logger logger = LoggerFactory.getLogger(HexHeadMessageHandleAdapter.class);
	
	private static HexHeadMessageHandleAdapter instance;
	
	private static String separator = "68";
	private Map<String,IMessageHandle> handles;
	
	public IMessageHandle adapter(String msg) {
		if(msg.isEmpty()) {
			return null;
		}
		String headStr = msg.substring(0, 2).toUpperCase();
		String head =chackHead(msg)==1?headStr.toUpperCase():"-1";
		IMessageHandle handle = handles.get(head);
		
		logger.error("apapter handle, head:{}, handle:{}" ,head, handle);
		return handle;
	}

	public static synchronized HexHeadMessageHandleAdapter newInstance(){
		if(instance==null){
			instance = new HexHeadMessageHandleAdapter();
			instance.setHandles(MessageHandles.newInstance().getHandles());
		}
		return instance;
	}
	
	public String getSeparator() {
		return separator;
	}

	public void setSeparator(String separator) {
		this.separator = separator;
	}

	public Map<String, IMessageHandle> getHandles() {
		return handles;
	}

	public void setHandles(Map<String, IMessageHandle> handles) {
		this.handles = handles;
	}

	public void registerMessageHandle(IMessageHandle messageHandle) {
		handles.put(messageHandle.name(),  messageHandle);
	}

	public IMessageHandle removeMessageHandle(String name) {
		return handles.remove(name);
	}

	public Collection<IMessageHandle> getMessageHandles() {
		return handles.values();
	}
	
	public static int chackHead(String msg) {
		if(msg.toUpperCase().startsWith(separator)) {
			return 1;	
		}else {
			return 0;
		}
	}
	
}
